<template>
    <rx-dialog :options="config" @close="close" @confirm="confirm" class="m-group-dialog">
        <div class="m-group-container">
            <div class="m-group-nav m-group-margin">
                <uni-breadcrumb separator="/">
                    <uni-breadcrumb-item
                        v-for="(route,index) in nav"
                        :key="index"
                        @click="navClick(route)"
                    >
                        {{ route.title }}
                    </uni-breadcrumb-item>
                </uni-breadcrumb>
            </div>
            <div class="m-group-padding m-group-search" v-if="nav[nav.length -1 ].type !== 'home'">
                <uni-easyinput
                    prefixIcon="search"
                    v-model="searchValue"
                    :placeholder="i18n('searchForBtn','搜索')+nav[1].title"
                    @clear="handleSearch"
                    confirm-type="search"
                    trim="all"
                    clearable
                ></uni-easyinput>
                <div class="search-btn" @click="handleSearch">{{i18n('searchForBtn','搜索')}}</div>
            </div>
            <div class="m-group-content">
                <div class="m-group-content-roll">
                    <template v-for="item of treeData">
                        <rx-group-item
                            :item="item"
                            :selectGroup="selectGroup"
                            :single="single"
                            @eventChange="handleItem($event,item)"
                        />
                    </template>
                    <template v-for="item of dimData">
                        <rx-group-item
                            :item="item"
                            label="title"
                            isType="dim"
                            :selectGroup="selectGroup"
                            @eventChange="eventChange($event,item)"/>
                    </template>
                </div>
            </div>
            <RxLoading v-if="Loading"></RxLoading>
            <div class="m-group-select">
                <ul class="m-group-select-box">
                    <li class="m-group-select-item" v-for="item of selectGroup">
                        {{ item.name }}
                    </li>
                </ul>
                <div class="m-group-select-all"
                     :class="{'m-select-all-color':selectGroup.length > 0}"
                     @click="openDialog"
                >
                    <span>{{i18n('selected','已选')}}（{{ selectGroup.length }}）</span>
                </div>
            </div>
        </div>
        <uni-popup
            ref="groupPopup"
            backgroundColor="#fff" @change="popupChange"
        >
            <div class="group-dialog-box">
                <div class="dialog-select-header" :class="{'dialog-select-header-active':dialogSelect.length > 0}">
                    <div class="select-title">{{i18n('selected','已选')}}</div>
                    <div class="del-select" @click="delSelect('select')">{{i18n('DeleteSelected','删除选中')}}</div>
                    <div class="del-all" @click="delSelect('all')">{{i18n('creanUp','清空')}}</div>
                </div>
                <div class="dialog-select-box">
                    <div v-for="item of selectGroup"
                         class="dialog-select-item"
                         :class="{'dialog-select-item-active':dialogSelect.includes(item.groupId)}"
                         @click="onDialogSelect(item)"
                    >
                        {{ item.name }}
                    </div>
                </div>
            </div>
        </uni-popup>
    </rx-dialog>
</template>

<script>
import Api from "@/api/Api.js";
import Util from "@/js/Util.js";
import RxGroupItem from "./RxGroupItem.vue";
import RxLoading from '@/components/RxLoading'
import RxDialog from "@/components/RxDialog";

export default {
    name: "RxGroupDialog",
    components: {
        RxGroupItem,
        RxLoading,
        RxDialog
    },
    data() {
        return {
            /*选择的数据*/
            selectGroup: [],
            /*头部标题*/
            config: {
                title: this.i18n('selectDepart','选择部门')
            },
            /*组织数据*/
            treeData: [],
            /*维度数据*/
            dimData: [],
            /*导航数据*/
            nav: [
                {title: this.i18n('RootOrganization','根组织'), key: '_indexHome', type: 'home'}
            ],
            queryParam: {Q_RANK_LEVEL__S_EQ: null},
            /*缓存当前维度的数据*/
            cacheTreeData: {},
            curSelectId: '',
            searchValue: '',
            /*弹窗中需要删除时选中的数据*/
            dialogSelect: [],
            Loading:true,
            /*维度ID*/
            dimId:'',
            /*是否单选*/
            single:false,
            /*租户ID*/
            tenantId:"",
            groupId:"",
            isExcludeThis:false,
            /*显示维度*/
            showDimId:true,
            /*指定等级*/
            initRankLevel:null,
            /**
             * 是否指定维度类型
             */
            orgGroupType:'',
            initGroups:[],
            eventName:''
        }
    },
    onLoad(params){
        let openGroupParams = uni.getStorageSync('openGroupParams')
        let obj = openGroupParams.params;
        //传入参数据
        for(let name in obj){
            this.$data[name] =obj[name]
        }
        this.eventName = openGroupParams.eventName;
        this.selectGroup = [...this.initGroups];
        this.loadDims()
    },
    methods: {
        i18n(name,text,key){
            return this.$ti18(name,text,"allLang",key);
        },
        confirm() {
            let self=this;
            uni.navigateBack({
                delta:1,
                success:function() {
                    uni.$emit(self.eventName,Util.deepClone(self.selectGroup))
                }
            })
        },
        close() {
            let self=this;
            uni.navigateBack({
                delta:1,
                success:function() {
                    uni.$emit(self.eventName,[])
                }
            })
        },
        //同时指定维度、维度等级，则以平铺显示
        isSelDimIdAndLevel() {
            if("selDim" ==this.orgGroupType  && this.showDimId && this.dimId && this.initRankLevel){
                return true;
            }
            return false;
        },
        openDialog() {
            this.$refs.groupPopup.open('bottom')
        },
        popupChange() {

        },
        navClick(route) {
            this.searchValue = '';
            if (this.cacheTreeData[route.key]) {
                let _data = Util.deepClone(this.cacheTreeData[route.key])
                if (route.type === 'home' && !this.groupId) {
                    this.dimData = _data;
                    this.treeData = []

                } else {
                    this.treeData = _data;
                    this.dimData = []
                }
            } else {
                this.curSelectId = route.key;
                this.queryParam.Q_DIM_ID__S_EQ = route.key;
                if (route.type === 'home') {
                    this.loadDims()
                } else if (route.type === 'dim') {
                    this.loadDeps(() => {
                        this.dimData = []
                    });
                } else {
                    this.callbackChildren({groupId: route.key}, () => {
                    })
                }
            }
            let idx = this.nav.findIndex(item => item.key === route.key)
            this.nav = this.nav.slice(0, idx + 1);
        },
        setCacheTreeData(dimId, treeData) {
            let _treeData = treeData ? treeData : this.treeData
            //缓存当前维度的数据
            this.cacheTreeData[dimId] = Util.deepClone(_treeData)
        },
        setNav({id, title, type}) {
            let select = this.nav.find(obj => obj.key === id)
            if (!select) {
                this.nav.push({key: id, title, type})
            }
        },
        handleClick(item) {
            this.setNav({id: item.dimId, title: item.title, type: 'dim'})
            this.curSelectId = item.dimId;
            this.queryParam.Q_DIM_ID__S_EQ = item.dimId;
            if (this.cacheTreeData[item.dimId]) {//如果有缓存数据
                this.treeData = Util.deepClone(this.cacheTreeData[item.dimId]);
                this.dimData = []
            } else {
                this.loadDeps(() => {
                    this.setCacheTreeData(this.curSelectId, this.treeData);
                    this.dimData = []
                });
            }
        },
        //判断下级是否有子级
        hasChildren(data) {
            for (let i = 0; i < data.length; i++) {
                if (data[i].childAmount > 0) {
                    data[i].children = [];
                }
            }
            return data;
        },
        handleData(data){
            //同时指定维度、维度等级，则以平铺显示
            if(this.isSelDimIdAndLevel()){
                this.treeData = data;
                return;
            }
            this.treeData = Util.listToTree(this.hasChildren(data), 'groupId', 'parentId');
        },
        loadDeps(callback) {
            if (this.dimId) {
                this.queryParam.Q_DIM_ID__S_EQ = this.dimId;
            }
            if (this.initRankLevel) {
                this.queryParam.Q_RANK_LEVEL__S_EQ = this.initRankLevel;
            }
            let self = this;
            if (this.groupId) {
                if (!this.isExcludeThis) {
                    Api.getOsGroupByGroupId(this.groupId, this.queryParam.Q_RANK_LEVEL__S_EQ).then(data => {
                        self.handleData(data);
                        callback()
                    });
                } else {
                    if(!this.queryParam.Q_DIM_ID__S_EQ){
                        return;
                    }
                    Api.getOsGroupByExcludeGroupId(this.groupId, this.queryParam.Q_DIM_ID__S_EQ, this.queryParam.Q_RANK_LEVEL__S_EQ, "0", this.tenantId).then(data => {
                        self.handleData(data);
                        callback()
                        console.log(self.treeData)
                    });
                }
            } else {
                if(!this.queryParam.Q_DIM_ID__S_EQ){
                    return;
                }
                Api.queryGroups(this.queryParam.Q_DIM_ID__S_EQ, this.queryParam.Q_RANK_LEVEL__S_EQ, "0", this.tenantId).then(result => {
                    let data = result.data;
                    if (data) {
                        self.handleData(data);
                        callback()
                        console.log(self.treeData)
                    }
                })
            }
        },
        setDimData(data) {
            let dimData = data.map(dim => {
                return {title: dim.name, key: dim.code, ...dim};
            })
            if(this.dimId){
                dimData = dimData.filter(item=>item.dimId === this.dimId);
                this.setNav({id: dimData[0].dimId, title: dimData[0].title, type: 'dim'})
            }
            this.dimData = dimData;
            this.setCacheTreeData('_indexHome', dimData)
        },
        loadDims() {
            if (this.dimId) {
                Api.getByDimIds(this.dimId).then(res => {
                    this.Loading = false
                    if(!this.groupId){
                        this.setDimData(res.data)
                    }
                    this.loadDeps(() => {
                        this.dimData = [];
                        if(this.groupId){
                            this.setCacheTreeData('_indexHome', this.treeData)
                        }
                    })
                })
            } else {
                Api.getDimList(this.tenantId).then(res => {
                    this.Loading = false
                    if(!this.groupId) {
                        this.setDimData(res.data)
                    }
                    this.loadDeps(() => {
                        this.dimData = []
                        if(this.groupId){
                            this.setCacheTreeData('_indexHome', this.treeData)
                        }
                    })
                })
            }
        },

        /*
        * 选中或者取消数据
        * */
        radioClick(item, field) {
            let value = item[field];
            let selectIndex = this.selectGroup.findIndex(obj => obj[field] === value)
            if (this.single) {
                if (selectIndex > -1) {
                    this.selectGroup = []
                } else {
                    this.selectGroup = [item]
                }
            } else {
                if (selectIndex > -1) {
                    this.selectGroup.splice(selectIndex, 1)
                    return;
                }
                this.selectGroup.push(item)
            }
        },
        handleSearch() {
            //点击搜索
            let {searchValue} = this;
            let last = this.nav[1];
            let id = last.key;
            this.queryParam.Q_DIM_ID__S_EQ = id;
            if (!searchValue) {
                this.navClick(last)
                return;
            }
            this.queryParam.Q_NAME__S_LK = searchValue;
            let self = this;
            let parameter = {
                pageNo: this.page,
                pageSize: this.pageSize,
                sortField: this.sortField,
                sortOrder: this.sortOrder == "descend" ? "desc" : "asc"
            };
            if (this.groupId) {
                this.queryParam.Q_GROUP_ID__S_NEQ = this.groupId;
            }
            if (this.tenantId) {
                this.queryParam.tenantId = this.tenantId;
            }

            parameter.params = this.queryParam
            Api.searchGroups(parameter).then(data => {
                self.treeData = Util.listToTree(self.hasChildren(data), 'groupId', 'parentId');
                Reflect.deleteProperty(self.cacheTreeData, id)
            });

        },
        groupSelect(item) {
            //选中
        },
        callbackChildren(item, callback) {
            let self = this;
            if (!this.isExcludeThis) {
                Api.queryGroups(this.queryParam.Q_DIM_ID__S_EQ, this.queryParam.Q_RANK_LEVEL__S_EQ, item.groupId, this.tenantId).then(result => {
                    let data = this.hasChildren(result.data);
                    this.treeData = [...data];
                    callback()
                })
            } else {
                Api.getOsGroupByExcludeGroupId(this.groupId, this.queryParam.Q_DIM_ID__S_EQ, this.queryParam.Q_RANK_LEVEL__S_EQ, item.groupId, this.tenantId).then(data => {
                    data = self.hasChildren(data);
                    this.treeData = [...data];
                    callback()
                });
            }
        },
        getGroupChildren(item) {
            //获取下级
            this.setNav({id: item.groupId, title: item.name, type: 'group'})
            this.curSelectId = item.groupId;
            this.queryParam.Q_DIM_ID__S_EQ = item.dimId;
            if (this.cacheTreeData[item.curSelectId]) {//如果有缓存数据
                this.treeData = Util.deepClone(this.cacheTreeData[item.curSelectId]);
            } else {
                this.callbackChildren(item, () => {
                    this.setCacheTreeData(this.curSelectId, this.treeData);
                })
            }
        },
        handleItem(type, item) {
            let obj = {
                radioClick: 'radioClick',
                handleClick: 'getGroupChildren'
            }
            this[obj[type]](item, 'groupId')
        },
        eventChange(type, item) {
            this[type](item)
        },
        onDialogSelect(item) {
            if (this.dialogSelect.includes(item.groupId)) {
                this.dialogSelect.splice(this.dialogSelect.indexOf(item.groupId), 1)
            } else {
                this.dialogSelect.push(item.groupId)
            }
        },
        delSelect(type) {
            if (type === 'all') {
                this.selectGroup = []
            } else {
                this.selectGroup = this.selectGroup.filter(item => !this.dialogSelect.includes(item.groupId));
            }
            this.dialogSelect = []
        }
    }
}
</script>

<style scoped>
.search-btn {
    padding: .4rem .6rem;
    color: #2979ff;
}

.m-select-all-color {
    color: #2979ff;
}

.m-group-select-all {
    display: flex;
    align-items: center;
    padding: 0.2rem 0 .2rem .4rem;
    border: 1px solid transparent;
    box-shadow: -5px 0 4px 0 rgba(0, 0, 0, 0.1);
}

.m-group-select-all > span {
    font-size: 0.8rem;
}

.m-group-select {
    display: flex;
    font-size: 12px;
    overflow: hidden;
    padding: 0 .4rem;
    height: 2.6rem;
}

.m-group-select-box {
    flex: 1;
    display: flex;
    align-items: center;
    overflow: hidden;
    white-space: nowrap;
}

.m-group-select-item {
    margin-right: .2rem;
    display: inline-block;
    font-size:0.8rem;
    box-sizing: border-box;
    padding: 0.2rem .6rem;
    border: 1px solid #e5e5e5;
    border-radius: .2rem;
    background: #fff;
}

.m-group-nav {
    background-color: #f4f5f6;

    overflow: auto;
}

.m-group-search {
    background-color: #fff;
}

.m-group-padding {
    padding: 0.59rem 0 .59rem 1rem;
    display: flex;
    align-items: center;
}

.m-group-margin {
    margin: 0.59rem 1rem;
}

.m-group-container {
    display: flex;
    height: 100%;
    flex-direction: column;
    border-top: 1px solid #f4f5f6;
}

.m-group-dialog >>> .m-mobile-roll {
    padding: 0;
}

.m-group-content {
    flex: 1;
    position: relative;
    background-color: #fff;
}

.m-group-content-roll {
    position: absolute;
    top: .59rem;
    left: 0;
    right: 0;
    bottom: 0;
    overflow: auto;
}

.dialog-select-header {
    padding: .4rem;
    font-size: 14px;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #f1f1f1;
}

.dialog-select-box {
    border-top-right-radius: 10px;
    border-top-left-radius: 10px;
    background-color: #fff;
    display: grid;
    grid-template-columns:repeat(4, 1fr);
    gap: .4rem;
    padding: .4rem .4rem .8rem .4rem;
}

.dialog-select-item {
    display: inline-block;
    padding: 0.2rem .6rem;
    border: 1px solid #f4f5f6;
    font-size: 0.8rem;
    border-radius: .2rem;
    text-align: center;
}

.del-select {
    margin-left: auto;
    margin-right: .4rem;
    padding: .4rem;
    color: #9f9090;
}

.del-all {
    padding: .4rem;
    color: #9f9090;
}

.dialog-select-item.dialog-select-item-active {
    background-color: #2979ff;
    color: #fff;
}

.dialog-select-header-active .del-select {
    color: #f3a73f;
}

.dialog-select-header-active .del-all {
    color: #e43d33;
}
</style>
